//
//  AppDelegate.m
//  预购清单
//
//  Created by  on 2022/10/15.
//

#import "AppDelegate.h"
#import "BaseTabBarViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setupLocalUser];
    BaseTabBarViewController *vc = [[BaseTabBarViewController alloc] init];
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.window = [[UIWindow alloc] initWithFrame:frame];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)setUser:(User *)user{
    _user = user;
    if ([_user.account isEqualToString:@""]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:accountkey];
    }else{
        [[NSUserDefaults standardUserDefaults] setValue:_user.account forKey:accountkey];
    }
    [self setupDefaultPrepay];
    [[NSNotificationCenter defaultCenter] postNotificationName:notifyUserUpdate object:nil];
}

- (void)setupLocalUser{
    bg_setDisableCloseDB(YES);
    NSString *account = [[NSUserDefaults standardUserDefaults] valueForKey:accountkey];
    if (account != nil && account.length > 0 && [account isEqualToString:@"去登录"] == NO) {
        [UserTool find:account complete:^(User * _Nonnull user) {
            self.user = user;
        }];
    }else{
        [UserTool register:@"O1234" psw:@"1234" complete:^(NSDictionary * _Nonnull dict) {}];
        self.user = [User new];
    }
}
///添加默认类型
- (void)setupDefaultPrepay{
    NSString * where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"account"),bg_sqlValue(APP.user.account)];
    NSInteger count = [PrepayType bg_count:nil where:where];
    if (count <= 0) {
        NSArray *titles = @[@"餐饮",@"零食",@"购物",@"社交"];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < titles.count; i ++) {
            PrepayType *model = [PrepayType new];
            model.name = titles[i];
            model.img = UIImageJPEGRepresentation([UIImage imageNamed:titles[i]], 1);
            model.account = self.user.account;
            [array addObject:model];
        }
        [PrepayType bg_saveOrUpdateArrayAsync:array complete:^(BOOL isSuccess) {}];
    }
}
@end
